#include "InetAddress.h"
#include<string.h>
InetAddress::InetAddress(uint16_t port, std::string ip) {
    // addr_初始化为0
    memset(&addr_, 0, sizeof(addr_));
    addr_.sin_family = AF_INET; // 设置地址族为IPv4
    addr_.sin_port = htons(port); // 将端口号转换为网络字节序
    addr_.sin_addr.s_addr = inet_addr(ip.c_str()); // 将IP地址转换为网络字节序
}

std::string InetAddress::toIp() const {
    char buf[INET_ADDRSTRLEN]; // INET_ADDRSTRLEN是IPv4地址的最大长度
    ::inet_ntop(AF_INET, &addr_.sin_addr, buf, sizeof(buf)); // 将网络字节序的IP地址转换为字符串
    return std::string(buf); // 返回IP地址字符串
}

uint16_t InetAddress::toPort() const {
    return ntohs(addr_.sin_port); // 将网络字节序的端口号转换为主机字节序并返回
}

std::string InetAddress::toIpPort() const {
    return toIp() + ":" + std::to_string(toPort()); // 返回IP地址和端口号的组合字符串
}

// #include <iostream>
// int main()
// {
//     InetAddress addr(8080);
//     std::cout << addr.toIpPort() << std::endl;

//     return 0;
// }